<template>
  <div class="club-posts-container">
    <div class="section-header">
      <h2>帖子管理</h2>
      <el-button type="primary" @click="createNewPost">
        <i class="el-icon-plus"></i> 新建帖子
      </el-button>
    </div>

    <!-- 帖子筛选 -->
    <div class="post-filter">
      <el-input
        v-model="searchQuery"
        placeholder="搜索帖子"
        prefix-icon="el-icon-search"
        clearable
        @clear="fetchClubPosts"
        class="search-input"
      ></el-input>
      <el-button type="primary" @click="searchPosts">搜索</el-button>
    </div>

    <!-- 帖子列表 -->
    <el-table
      :data="searchQuery.trim() ? filteredPosts : posts"
      style="width: 100%"
      stripe
      :header-cell-style="{ backgroundColor: '#1f1b24', color: '#ffffff' }"
      :cell-style="{ backgroundColor: '#28232e', color: '#b0bec5' }"
      v-loading="loading"
    >
      <el-table-column label="封面" min-width="100">
        <template #default="scope">
          <img
            :src="getImageUrl(scope.row.image)"
            alt="帖子封面"
            style="width: 50px; height: 50px; object-fit: cover; border-radius: 4px;"
          >
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" min-width="150"></el-table-column>
      <el-table-column prop="description" label="内容" min-width="200"></el-table-column>
      <el-table-column prop="author" label="发布者" min-width="120">
        <template #default="scope">
          <div style="display: flex; align-items: center;">
            <img
              :src="getImageUrl(scope.row.authorimg, 'avatar')"
              alt="用户头像"
              style="width: 24px; height: 24px; border-radius: 50%; margin-right: 5px;"
            >
            {{ scope.row.author }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="发布时间" min-width="160">
        <template #default="scope">
          {{ formatDate(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="互动数" min-width="150">
        <template #default="scope">
          <span style="margin-right: 15px;">
            <i class="el-icon-star-on" style="color: #E6A23C;"></i>
            点赞 {{ scope.row.likedBy?.length || 0 }}
          </span>
          <span>
            <i class="el-icon-chat-dot-round" style="color: #409EFF;"></i>
            评论 {{ scope.row.comments?.length || 0 }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160" fixed="right">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="viewPost(scope.row)"
          >查看</el-button>
          <el-button
            size="small"
            type="danger"
            @click="confirmDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="totalItems"
        background
      ></el-pagination>
    </div>

    <!-- 查看帖子详情 -->
    <el-dialog
      title="帖子详情"
      v-model="showPostDialog"
      width="800px"
    >
      <div v-if="selectedPost" class="post-detail">
        <h2 class="post-title">{{ selectedPost.title }}</h2>

        <div class="post-author-info">
          <div class="author-avatar-container">
            <img
              :src="getImageUrl(selectedPost.authorimg, 'avatar')"
              alt="作者头像"
              class="author-avatar-lg"
            />
          </div>
          <div class="author-detail">
            <div class="author-name">{{ selectedPost.author }}</div>
            <div class="post-time">{{ formatDate(selectedPost.createdAt) }}</div>
          </div>
        </div>

        <div v-if="selectedPost.image" class="post-image-container">
          <img
            :src="getImageUrl(selectedPost.image)"
            alt="帖子图片"
            class="full-post-image"
          />
        </div>

        <div class="post-content">
          {{ selectedPost.description }}
        </div>

        <div class="post-stats">
          <div class="stat-item">
            <i class="el-icon-star-on"></i>
            <span>{{ selectedPost.likes || 0 }} 次点赞</span>
          </div>
          <div class="stat-item">
            <i class="el-icon-chat-dot-round"></i>
            <span>{{ selectedPost.comments?.length || 0 }} 条评论</span>
          </div>
        </div>

        <!-- 评论列表 -->
        <div class="comments-section" v-if="selectedPost.comments && selectedPost.comments.length > 0">
          <h3>评论 ({{ selectedPost.comments.length }})</h3>
          <div class="comment-item" v-for="comment in selectedPost.comments" :key="comment.id">
            <div class="comment-content">{{ comment.text }}</div>
          </div>
        </div>
        <div class="no-comments" v-else>
          暂无评论
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showPostDialog = false">关闭</el-button>
          <el-button type="danger" @click="deleteSelectedPost">删除帖子</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      title="确认删除"
      v-model="showDeleteDialog"
      width="30%"
      :close-on-click-modal="false"
    >
      <p>确定要删除帖子 "{{ postToDelete?.title }}" 吗？此操作不可撤销。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDeleteDialog = false">取消</el-button>
          <el-button type="danger" @click="deletePost">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, defineProps } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 接收社团ID属性
const props = defineProps({
  clubId: {
    type: [String, Number],
    required: true
  }
})

const router = useRouter()

// 状态变量
const loading = ref(false)
const posts = ref([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalItems = ref(0)
const showPostDialog = ref(false)
const showDeleteDialog = ref(false)
const selectedPost = ref(null)
const postToDelete = ref(null)


// 过滤后的帖子列表
const filteredPosts = computed(() => {
  if (!searchQuery.value.trim()) return posts.value

  const query = searchQuery.value.toLowerCase()
  return posts.value.filter(post =>
    post.title.toLowerCase().includes(query) ||
    post.description.toLowerCase().includes(query) ||
    post.author.toLowerCase().includes(query)
  )
})

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString()
}

// 处理图片URL
const getImageUrl = (imageId, type = 'post') => {
  if (!imageId) {
    // 返回默认图片
    if (type === 'avatar') {
      try {
        return require('@/assets/icons/touxiang.png');
      } catch (e) {
        return 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'; // Element Plus 默认头像
      }
    } else {
      try {
        return require('@/assets/icons/default-post.png');
      } catch (e) {
        return 'https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png'; // 默认帖子图片
      }
    }
  }

  // 如果已经是完整URL，直接返回
  if (imageId.startsWith('http')) return imageId;

  // 否则根据ID构建API URL
  return `http://localhost:5000/uploads/${imageId}`;
}

// 获取社团帖子
const fetchClubPosts = async () => {
  const id = props.clubId
  loading.value = true
  try {
    const response = await axios.get(`http://localhost:5000/clubs/${id}/posts`, {
      params: {
        page: currentPage.value,
        limit: pageSize.value
      }
    });

    // 打印完整的响应数据以便调试
    console.log('API响应数据:', response.data);

    // 检查数据结构
    if (Array.isArray(response.data)) {
      // 如果响应是数组形式
      posts.value = response.data;
      totalItems.value = response.data.length;
    } else if (response.data.posts) {
      // 如果响应有posts属性
      posts.value = response.data.posts;
      totalItems.value = response.data.total || response.data.posts.length;
    } else if (response.data && typeof response.data === 'object' && 'length' in response.data) {
      // 如果响应是类数组对象（如截图中显示的格式）
      const dataArray = [];
      // 遍历对象中的每个条目，跳过length等非数字或特殊属性
      for (const key in response.data) {
        if (!isNaN(parseInt(key)) && typeof response.data[key] === 'object') {
          dataArray.push(response.data[key]);
        }
      }
      posts.value = dataArray;
      totalItems.value = dataArray.length;
    } else {
      // 其他情况
      posts.value = response.data || [];
      totalItems.value = response.data?.total || 0;
    }

    // 检查图片字段
    posts.value.forEach((post, index) => {
      console.log(`帖子 ${index + 1} 封面:`, post.image);
      console.log(`帖子 ${index + 1} 用户头像:`, post.authorimg);
    });

  } catch (error) {
    console.error('获取社团帖子失败:', error);
    ElMessage.error('获取社团帖子失败')
  } finally {
    loading.value = false
  }
};

// 搜索帖子
const searchPosts = () => {
  if (searchQuery.value.trim()) {
    // 使用计算属性过滤本地数据
    const filtered = filteredPosts.value;
    console.log('搜索结果:', filtered);

    // 如果需要在界面上显示过滤后的结果，但不改变原数据
    if (filtered.length > 0) {
      ElMessage.success(`找到 ${filtered.length} 条相关帖子`);
    } else {
      ElMessage.info('未找到相关帖子');
    }
  } else {
    // 如果搜索框为空，重新获取所有帖子
    fetchClubPosts();
  }
}

// 分页处理
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchClubPosts()
}

// 查看帖子详情
const viewPost = (post) => {
  selectedPost.value = post
  showPostDialog.value = true
}

// 确认删除帖子
const confirmDelete = (post) => {
  postToDelete.value = post
  showDeleteDialog.value = true
}

// 删除当前查看的帖子
const deleteSelectedPost = () => {
  if (selectedPost.value) {
    postToDelete.value = selectedPost.value;
    showPostDialog.value = false;
    showDeleteDialog.value = true;
  }
}

// 删除帖子
const deletePost = async () => {
  if (!postToDelete.value) return

  try {
    // 调用删除帖子API
    const response = await axios.delete(`http://localhost:5000/posts/${postToDelete.value._id}`);

    // 如果API调用成功，从本地列表中移除该帖子
    if (response.status === 200) {
      // 从本地列表中移除该帖子
      posts.value = posts.value.filter(post => post._id !== postToDelete.value._id);

      ElMessage.success('帖子删除成功');
      showDeleteDialog.value = false;
      // 如果当前正在查看被删除的帖子，关闭详情对话框
      if (showPostDialog.value && selectedPost.value && selectedPost.value._id === postToDelete.value._id) {
        showPostDialog.value = false;
      }
      postToDelete.value = null;
    }
  } catch (error) {
    console.error('删除帖子失败', error);
    ElMessage.error(error.response?.data?.message || '删除帖子失败');
  }
}

// 创建新帖子
const createNewPost = () => {
  // 实际应用中可能跳转到帖子发布页面
  router.push(`/publish?clubId=${props.clubId}`)
}

onMounted(() => {
  fetchClubPosts()
})
</script>

<style scoped>
.club-posts-container {
  width: 100%;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h2 {
  margin: 0;
  font-size: 20px;
  color: #ffffff;
}

.post-filter {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 帖子详情样式 */
.post-detail {
  padding: 20px;
  background-color: #1f1b24;
  border-radius: 8px;
}

.post-title {
  color: #fff;
  font-size: 24px;
  margin-bottom: 20px;
}

.post-author-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.author-avatar-container {
  margin-right: 15px;
}

.author-avatar-lg {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
}

.author-detail {
  display: flex;
  flex-direction: column;
}

.author-name {
  color: #fff;
  font-weight: bold;
  margin-bottom: 5px;
}

.post-time {
  color: #999;
  font-size: 14px;
}

.post-image-container {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.full-post-image {
  width: 100%;
  max-height: 400px;
  object-fit: contain;
}

.post-content {
  line-height: 1.6;
  margin-bottom: 20px;
  color: #b0bec5;
}

.post-stats {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  color: #b0bec5;
}

.post-stats i {
  margin-right: 5px;
}

.comments-section {
  margin-top: 30px;
  border-top: 1px solid #333;
  padding-top: 20px;
}

.comments-section h3 {
  margin-bottom: 15px;
  color: #ffffff;
  font-size: 18px;
}

.comment-item {
  padding: 10px 0;
  border-bottom: 1px solid #333;
}

.comment-content {
  color: #b0bec5;
}

.no-comments {
  text-align: center;
  color: #777;
  padding: 20px 0;
}
</style>
